#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import pymysql
import sys


class XMySQLUtils(object):

    @staticmethod
    def db_connect(p_user = None, p_host = None, p_port = 3306, p_passwd = None, p_db_name = None, p_charset = None):
        """

        :param p_user:
        :param p_host:
        :param p_port:
        :param p_passwd:
        :param p_db_name:
        :param p_charset:
        :return: success    : true indicate connect success, otherwise not.
                 conn       : connection
                 cursor     : cursor

        """
        success = False
        conn = None
        cur = None
        try:
            conn = pymysql.connect(user=p_user, host=p_host, port=p_port, passwd=p_passwd, db=p_db_name, charset=p_charset)
            cur = conn.cursor()
            success = True
        except Exception as e:
            print
            e.message
            import traceback
            traceback.print_exc()
            if conn is not None:
                conn.rollback()
            success = False
            conn = None
            cur = None

        return success, conn, cur

    @staticmethod
    def db_close(p_cursor=None, p_conn=None):
        """

        :param p_cursor:
        :param p_conn:
        :return:
        """
        try:
            p_cursor.close()
            p_conn.close()
        except Exception as e:
            print >> sys.stderr, "MySQLException", str(e)

    @staticmethod
    def execute_sql(p_sql = None, p_cur=None, p_conn=None):
        success = False
        if p_sql is not None:
            try:
                p_cur.execute(p_sql)
                p_conn.commit()
                success = True
            except Exception as e:
                success = False
                print >> sys.stderr, "MySQLException", p_sql, str(e)
        return success

    @staticmethod
    def executemany_sql(p_sql = None, p_cur=None, p_conn=None, p_param = None):
        success = False
        if p_sql is not None and p_param is not None and len(p_param) > 0:
            try:
                p_cur.executemany(p_sql, p_param)
                p_conn.commit()
                success = True
            except Exception as e:
                success = False
                print >> sys.stderr, "MySQLException", p_sql, str(e)
        return success

    @staticmethod
    def fetchall_sql(p_sql = None, p_cur=None):
        success = False
        results = list()
        try:
            p_cur.execute(p_sql)
            results = list(p_cur.fetchall())
            success = True
        except Exception as e:
            success = False
            results = list()
            print >> sys.stderr, "MySQLException", p_sql, str(e)
        return success, results
